﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Ledict.Utility.Extension
{
    /// <summary>
    /// XML格式通用操作类
    /// </summary>
    /// <remarks>
    /// Create Date：2014-02-03
    /// Create Author：Zhangpeng
    /// Version：1.0
    /// </remarks>
    public static class XmlExtension
    {
        #region Method
        /// <summary>
        /// 指定对象序列化成XML字符串
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToXml(this object obj)
        {
            var ser = new XmlSerializer(obj.GetType());
            var stream = new MemoryStream();
            ser.Serialize(stream, obj);
            return Encoding.UTF8.GetString(stream.ToArray());
        }

        /// <summary>
        /// XML文档反序列化成指定对象
        /// </summary>
        /// <typeparam name="TResult">指定对象类型</typeparam>
        /// <param name="xml">XML文档</param>
        /// <returns>指定对象</returns>
        public static TResult FromXml<TResult>(this string xml)
        {
            var ser = new XmlSerializer(typeof(TResult));
            var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml));

            return (TResult)ser.Deserialize(ms);
        }

        /// <summary>
        /// 将对象转换成xml，并储存在硬盘
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <param name="path">储存的文件地址</param>
        public static void SaveToXml(this object obj, string path)
        {
            var ser = new XmlSerializer(obj.GetType());
            var xmlwriter = new XmlTextWriter(path, Encoding.UTF8);
            ser.Serialize(xmlwriter, obj);
            xmlwriter.Close();
        }

        /// <summary>
        /// 从硬盘读取xml文件并转换成对象
        /// </summary>
        /// <typeparam name="TResult">The type of the result.</typeparam>
        /// <param name="path">xml文件地址</param>
        /// <returns>对象</returns>
        public static TResult LoadFromXml<TResult>(this string path)
        {
            var xmlreader = new XmlTextReader(path);
            try
            {
                var ser = new XmlSerializer(typeof(TResult));


                if (!ser.CanDeserialize(xmlreader))
                {
                    throw new ArgumentException("无法反序列化为指定类型," + path + " ->" + typeof(TResult));
                }
                var tResult = (TResult)ser.Deserialize(xmlreader);
                xmlreader.Close();
                return tResult;
            }
            catch (Exception)
            {
                xmlreader.Close();
                TResult t = default(TResult);
                return t;
            }


        }
        #endregion

    }
}
